// DDXray.cpp: implementation of the DDSocket.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "DDXray.h"

BOOL ChangeMaxMA(zkRayCtrl *pCtrl,zkRayCfg *pCfg)
{
	BOOL bRet = FALSE;

	int   k=0; 
	int   nkv1,nkv2,nkv;
	float fR = 0,fmaMax=0;

	if( pCtrl->nFocus ) //big
	{
		if( pCtrl->fKV < pCfg->fFOCKV[0] )
		{
			pCtrl->fKV = pCfg->fFOCKV[0];
		}
		else if( pCtrl->fKV > pCfg->fFOCKV[3] )
		{
			pCtrl->fKV = pCfg->fFOCKV[3];
		}

		nkv = (int)pCtrl->fKV;

		for(k=0;k<3;k++)
		{
			if( pCfg->fFOCKV[k] <= pCtrl->fKV && pCtrl->fKV <= pCfg->fFOCKV[k+1] )
			{
				nkv1 = (int)pCfg->fFOCKV[k];
				nkv2 = (int)pCfg->fFOCKV[k+1];
				nkv  = nkv2 - nkv1;
				if( nkv == 0 )
				{
					fR = 0;
				}
				else
				{
					fR = pCfg->fFOCMA[k] - pCfg->fFOCMA[k+1];
					fR /= nkv;
				}

				nkv = (int)( pCtrl->fKV + 0.99f);

				fmaMax = pCfg->fFOCMA[k+1];
				if( nkv == nkv1 )
				{
                   fmaMax = pCfg->fFOCMA[k];
				}
				else if( nkv == nkv2 )
				{

				}
				else
				{
					for(int i=nkv1;i<nkv2;i++)
					{
						if( i == nkv ) 
						{
							fmaMax += fR * (nkv2-i);
							break;
						}
					}
				}

				if( pCtrl->fMA > fmaMax )
				{
					pCtrl->fMA = fmaMax;

					bRet = TRUE;
				}
				break;
			}
		}	
	}
	else
	{
		if( pCtrl->fKV < pCfg->fsfockv[0] )
		{
			pCtrl->fKV = pCfg->fsfockv[0];
		}
		else if( pCtrl->fKV > pCfg->fsfockv[3] )
		{
			pCtrl->fKV = pCfg->fsfockv[3];
		}

		nkv = (int)pCtrl->fKV;

		for(k=0;k<3;k++)
		{
			if( pCfg->fsfockv[k] <= pCtrl->fKV && pCtrl->fKV <= pCfg->fsfockv[k+1] )
			{
				nkv1 = (int)pCfg->fsfockv[k];
				nkv2 = (int)pCfg->fsfockv[k+1];
				nkv  = nkv2 - nkv1;
				if( nkv == 0 )
				{
					fR = 0;
				}
				else
				{
					fR = pCfg->fsfocma[k] - pCfg->fsfocma[k+1];
					fR /= nkv;
				}

				nkv = (int)( pCtrl->fKV + 0.99f);
				
				fmaMax = pCfg->fsfocma[k+1];
				if( nkv == nkv1 )
				{
					fmaMax = pCfg->fsfocma[k];
				}
				else if( nkv == nkv2 )
				{
 
				}
				else
				{
					for(int i=nkv1;i<nkv2;i++)
					{
						if( i == nkv ) 
						{
							fmaMax += fR * (nkv2-i);
							break;
						}
					}
				}

				if( pCtrl->fMA > fmaMax )
				{
					pCtrl->fMA = fmaMax;

					bRet = TRUE;
				}

				break;
			}
		}	
	}

	return bRet;
}